package yxy.banana.server.management;

import java.util.HashMap;
import java.util.Set;

public class Clustered<K, V> {
	protected final HashMap<K, Bundled<V>> mapping = new HashMap<>();

	public synchronized void add(K key, V value) {
		Bundled<V> bundled = this.mapping.get(key);
		if (bundled == null) {
			bundled = new Bundled<>();
		}
		bundled.add(value);
		this.mapping.put(key, bundled);
	}

	public synchronized void remove(K key, V value) {
		Bundled<V> bundled = this.mapping.get(key);
		if (bundled != null) {
			bundled.remove(value);
			if (bundled.size() <= 0) {
				this.mapping.remove(key);
			}
		}
	}

	public int mapped() {
		return this.mapping.size();
	}

	public synchronized int bundled(K key) {
		Bundled<V> bundled = this.mapping.get(key);
		if (bundled != null) {
			return bundled.size();
		} else {
			return 0;
		}
	}

	public synchronized int clustered() {
		int count = 0;
		Set<K> keys = this.mapping.keySet();
		for (K key : keys) {
			Bundled<V> bundled = this.mapping.get(key);
			if (bundled != null) {
				count += bundled.size();
			}
		}
		return count;
	}

	public synchronized V balance(K key) {
		Bundled<V> bundled = this.mapping.get(key);
		if (bundled != null) {
			return bundled.balance();
		} else {
			return null;
		}
	}
}
